<?php
/*script posting a message to feed, takes following GET parameters:
 *id - an ID of the user that the message will be posted to
 *sender_id - an ID of the user that will post the message
 *message - message text
 */
include 'configuration.php';

if(isset($_GET['postee_id']) && isset($_GET['message']) && isset($_GET['poster_id']))
{		
	//if all params set, post
	$postee_id = $_GET['postee_id'];
	$message = $_GET['message'];
	$poster_id = $_GET['poster_id'];
	
	//retrieve the access token
	$link = mysql_connect('localhost', $DBUSER, $DBPASS) or die('Could not connect: ' . mysql_error());
	mysql_select_db('facebook') or die('Could not select database');
	
	$query = "select name, access_token from users where id=$poster_id";
	$result = mysql_query($query) or die('Query failed: ' . mysql_error());
	$row = mysql_fetch_array($result, MYSQL_NUM);
	$poster_name = $row[0];
	$token = $row[1];
	
	if ($poster_id!=$postee_id)
	{
		$query = "select name from users where id=$postee_id";
		$result = mysql_query($query) or die('Query failed: ' . mysql_error());
		$row = mysql_fetch_array($result, MYSQL_NUM);
		$postee_name = $row[0];
	}
	else
	{
		$postee_name = $poster_name;
	}
	
	$message = str_replace("<poster>",$poster_name,$message);
	$message = str_replace("<postee>",$postee_name,$message);
	
	
	//echo "Sending message '$message' to user id $postee_id with token $token</br>\n";
	
	//send the message
	do_post_request("https://graph.facebook.com/$postee_id/feed", "access_token=$token&message=$message");
	
	mysql_free_result($result);
	mysql_close($link);
}

function do_post_request($url, $data)
{
	//sends a post request to $url with post data $data
	define('POSTURL', $url);
	define('POSTVARS', $data);  // POST VARIABLES TO BE SENT
	
	$ch = curl_init(POSTURL);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, POSTVARS);
	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$out = curl_exec($ch);
	$response = json_decode($out);
	if (isset($response->{'error'}))
	{
		echo 'fail';
	}
	else
	{
		echo 'victory';
	}
	curl_close($ch);
}

?>
